package com.liuyfly.leetcode.questions;

import com.liuyfly.leetcode.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author liuyangfang at 2022-08-23 10:18
 */
@Slf4j
public class Question0189 {
    /**
     * 给你一个数组，将数组中的元素向右轮转 k 个位置，其中 k 是非负数。<br/>
     * <br/>
     * 链接： https://leetcode.cn/problems/rotate-array/
     */
    public static void rotate(int[] nums, int k) {
        if (k <= 0 || nums.length <= 1) {
            return;
        }
        k = k % nums.length;
        int[] nums2 = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            int index = i + k;
            if (index >= nums.length) {
                index = index % nums.length;
            }
            nums2[index] = nums[i];
        }
        System.arraycopy(nums2, 0, nums, 0, nums.length);
    }

    public static void rotate2(int[] nums, int k) {
        if (k <= 0 || nums.length <= 1) {
            return;
        }
        k = k % nums.length;
        reverse(nums,0,nums.length-k-1);
        reverse(nums,nums.length-k,nums.length-1);
        reverse(nums,0,nums.length-1);
    }

    public static void reverse(int[] nums, int start, int end) {
        int flag = 0;
        int middle = (start+end)/2;
        while (flag<=middle-start){
            int temp = nums[start+flag];
            nums[start+flag]=nums[end-flag];
            nums[end-flag]=temp;
            flag++;
        }
    }

    public static void main(String[] args) {
        int[] nums = { 1, 2, 3, 4, 5, 6, 7,8 };
        rotate2(nums, 13);
        log.info("{}", JsonUtil.toJson(nums));
    }
}
